home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news
- From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
- Newsgroups: comp.lang.c++
- Subject: Re: [Q] new-allocated objects within try block
- Date: Sun, 21 Jan 1996 14:04:00 +0100
- Organization: Fachbereich Informatik, TH Darmstadt
- Message-ID: <310239C0.41C67EA6@intellektik.informatik.th-darmstadt.de>
- References: <monnet-2001962147210001@alpnet76.alpes-net.fr>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b5 (X11; I; SunOS 4.1.3 sun4m)
-
- Nicolas Monnet wrote:
- >
- > Here's the problem I'm facing -- it's probably a bad approach, it's even
- > possibly answered in some faq but...
- >
- > I need to allocate an object with new, and delete it in the same block,
- > as if it was allocated on the stack.
- > Why? Well, I'm using an abstract base class, and I have different descendents,
- > and, of course, I create one of them. Example:
- >
- > class ABC { public: virtual void DoSomething() = 0; };
- > class A : public ABC { public: virtual void DoSomething(); };
- > class B : public ABC { public: virtual void DoSomething(); };
- >
- > (...)
- > try {
- > ABC *p;
- > if (test) {
- > ..
- > p = new A;
- > } else {
- > ...
- > p = new B;
- > }
- > ...
- > throw sthg;
- > ...
- > p->DoSomething();
- > delete p;
- > } catch (...) {
- >
- > }
- >
- > Then, *p is not properly destroyed, isn't it?
- >
- > What is another way of doing it?
- >
-
- Wrap the object, using a class like 'auto_ptr'.
- In addition your base-class 'ABC' must provide
- a virtual dtor.
-
- Enno
-